import { call, put, putResolve, takeEvery } from 'redux-saga/effects';
import * as actionTypes from '@src/model/actionType';
import * as API from '@src/api/index';
import { get as _get } from 'lodash';

function* fetchChainDecimal(action) {
  try {
    const data = yield call(API.getChainDecimal, action.params);
    yield put({
      type: actionTypes.chainDecimal,
      payload: {
        BlockHeight: _get(data, ['Data', 'BlockHeight'], 0),
        OrgNum: _get(data, ['Data', 'OrgNum'], 0),
        ContractNum: _get(data, ['Data', 'ContractNum'], 0),
        TransactionNum: _get(data, ['Data', 'TransactionNum'], 0),
        ContractExecNum: _get(data, ['Data', 'ContractExecNum'], 0),
        TxNum: _get(data, ['Data', 'TxNum'], 0),
      },
    });
  } catch (err) {
    console.error(err);
  }
}

function* fetchBlockDetail(action) {
  const { params } = action;
  try {
    const data = yield call(API.getBlockDetail, params);
    yield putResolve({
      type: actionTypes.blockDetail,
      payload: {
        BlockHash: _get(data, ['Data', 'BlockHash'], ''),
        PreBlockHash: _get(data, ['Data', 'PreBlockHash'], ''),
        BlockHeight: _get(data, ['Data', 'BlockHeight'], 0),
        TxCount: _get(data, ['Data', 'TxCount'], 0),
        TxMerkleHash: _get(data, ['Data', 'TxMerkleHash'], ''),
        ProposalNodeId: _get(data, ['Data', 'ProposalNodeId'], ''),
        Dag: _get(data, ['Data', 'Dag'], ''),
        RwSetHash: _get(data, ['Data', 'RwSetHash'], ''),
        Timestamp: _get(data, ['Data', 'Timestamp'], 0),
        OrgId: _get(data, ['Data', 'OrgId'], ''),
      },
    });
  } catch (err) {
    console.error(err);
  }
}

const sagas = [
  takeEvery(actionTypes.fetchChainDecimal, fetchChainDecimal),
  takeEvery(actionTypes.fetchBlockDetail, fetchBlockDetail),
];

export default sagas;
